<template>
  <div id="dynamicDetail">
    <router-link :to="'/' + this.backTo">
      <button @click="back" id="back">返回</button>
    </router-link>
    <div class="wrap">
      <h2 class="title">{{ info.title }}</h2>
      <p class="time">
        <span id="user">{{ info.username }}</span>
        <span>{{ info.creationTime }}</span>
        <span @click="delDynamic(info.id)" v-if="info.userId == this.userid">
          删除
        </span>
      </p>
      <template v-if="info.hasPicture == 1">
        <img
          v-for="(item, index) in info.urls"
          :key="'url' + index"
          :src="'http://www.rushmc.top/' + item"
          class="pic"
        />
      </template>
      <p class="content">{{ info.content }}</p>
    </div>
    <div id="com_reply">
      <comment
        :commentData="item"
        ref="comment"
        v-for="(item, index) in this.commentsData"
        :key="index"
        @update="update"
      ></comment>
      <div id="addWrap">
        <textarea name="" id="" v-model="comment"></textarea>
        <button @click="addComment" id="addComment">评论</button>
      </div>
    </div>
  </div>
</template>

<script>
import comment from "./comment";
import { Request } from "../until/request";
export default {
  name: "dynamicDetails",
  props: [],
  components: {
    comment
  },
  data() {
    return {
      //该动态数据
      info: {},
      //输入评论内容
      comment: "",
      //所有评论数据 length:评论个数
      //请求数据结束后填入
      commentsData: [],
      //当前用户
      userid: 0,
      //返回哪个页面
      backTo: ""
    };
  },
  computed: {},
  mounted() {
    //记录返回哪个页面
    this.backTo = sessionStorage.getItem("func");
    //记录当前用户
    this.userid = sessionStorage.getItem("userId");
    //获取该条动态数据
    this.info = JSON.parse(sessionStorage.getItem("data"));
    //处理creationTime
    this.info.creationTime = this.info.creationTime.slice(0, 10);
    //请求评论数据
    this.request("post", "getReplyById");
  },
  methods: {
    //删除动态
    delDynamic(id) {
      let req = new Request();
      let formdata = new FormData();
      formdata.append("id", id);
      req
        .send("post", "api/api/dynamicState/delete", formdata)
        .then(res => {
          if (res.data.code == 200) {
            if (this.backTo == "Index") {
              //跳转回第一页
              sessionStorage.setItem("currentPage", 1);
              sessionStorage.setItem("currentArr", 0);
              window.location.href = "#/index";
            } else {
              //跳转回第一页
              sessionStorage.setItem("_currentPage", 1);
              sessionStorage.setItem("_currentArr", 0);
              window.location.href = "#/myDouban/myDynamic";
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    addComment(e) {
      let req = new Request();
      let formdata = new FormData();
      formdata.append("dynamicStateId", this.info.id);
      formdata.append("replyerId", sessionStorage.getItem("userId"));
      formdata.append("beReplyerId", this.info.userId);
      formdata.append("commentsContent", this.comment);
      req
        .send("post", `/api/api/comment/insert`, formdata)
        .then(res => {
          console.log(res);
          //清空评论框内容
          this.comment = "";
          //重新请求刷新内容
          this.request("post", "getReplyById");
        })
        .catch(err => {
          console.log(err);
        });
    },
    //comment子组件调用 重新请求刷新内容
    update() {
      console.log("re");
      this.request("post", "getReplyById");
    },
    //处理评论数据 data为处理好的数据
    process(arr, data) {
      arr.forEach((item, index) => {
        //设置replies字段
        item.replies = [];
        data.forEach((el, index) => {
          //el.replyId == item.id表示el是对item的评论 则将el压入item.replies
          if (el.replyId == item.id) {
            item.replies.push(el);
            //递归深层循环往item.replies里面嵌套replies
            //类似树结构
            this.process(item.replies, data);
          } else {
            return;
          }
        });
      });
      // console.log(data);
    },
    //请求回调
    req_callback(data) {
      //处理评论数据
      this.process(data, data);

      //筛选出评论 评论replyId=0
      //处理好的评论数据放在commentsData
      this.commentsData = data.filter((item, index) => {
        return item.replyId == 0;
      });

      console.log(this.commentsData);
      setTimeout(() => {
        if (this.$refs.comment) {
          //循坏每个comment组件
          this.$refs.comment.forEach((comment, index) => {
            //如果存在replies
            console.log(comment._props["commentData"].replies);
            comment.clearReplies();
            //处理每个comment中的评论数据
            comment.processData(comment._props["commentData"].replies);
            // if (comment._props["commentData"].replies.length != 0) {
            //   comment.clearReplies();
            //   //处理每个comment中的评论数据
            //   comment.processData(comment._props["commentData"].replies);
            // } else {

            // }
          });
        }
      }, 0);
    },
    request(method, url) {
      let req = new Request();
      let formdata = new FormData();
      formdata.append("dynamicId", this.info.id);
      req
        .send(method, `/api/api/${url}`, formdata)
        .then(res => {
          if (res.data.code == 1000) {
            let data = res.data.data;
            console.log(res);
            this.req_callback(data);
          } else {
            let data = [];
            this.req_callback(data);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    back() {}
  }
};
</script>

<style scoped>
#dynamicDetail {
  /* background: pink; */
  display: flex;
  flex-direction: column;
  /* align-items: center; */
}
#dynamicDetail #back {
  width: 4rem;
  height: 2rem;
  border: none;
  outline: none;
  border-radius: 0.4rem;
  color: white;
  background: #4da6ff;
  cursor: pointer;
}
#dynamicDetail #back:hover {
  background: #007fff;
}
.wrap {
  width: 80%;
  display: flex;
  flex-direction: column;
  align-self: center;
  /* height: 50rem; */
  /* background: lightblue; */
}
.title {
  padding: 2rem 0 0.5rem;
  align-items: flex-start;
  /* background: pink; */
}
.time {
  font-size: 0.8rem;
  color: #999;
  align-items: flex-start;
}
.time span:nth-child(3) {
  font-style: italic;
  cursor: pointer;
}
.time span:nth-child(3):hover {
  color: black;
}
.time #user {
  color: #1a8cff;
}
.content {
  padding: 1rem 0 5rem;
}
input {
  width: 12rem;
  height: 5rem;
  border: 1px solid #ccc;
}
#addWrap {
  width: 80%;
  padding: 3rem 0;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  /* background: lightblue; */
}
#addWrap textarea {
  height: 4.2rem;
  width: 50rem;
  border: 1px solid #999;
  margin-right: 1rem;
  padding: 0.4rem;
  outline: none;
}
#addComment {
  width: 3rem;
  height: 3rem;
  box-sizing: content-box;
  padding: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 0.4rem;
  color: white;
  font-size: 1.2rem;
  background: #4da6ff;
}
#addComment:hover {
  background: #007fff;
}
</style>